// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuetify from 'vuetify'
import config from './config'
import MyComponent from './components/MyComponent'
import './http';
import 'vuetify/dist/vuetify.min.css'
import qs from 'qs'
import './assets/material.css'

//高亮XML标签
import VueHighlightJS from 'highlight.js'
//样式文件，我选了a11y-light.css，可选择文件里其他高亮样式css
import 'highlight.js/styles/a11y-light.css'
Vue.use(VueHighlightJS);
//自定义指令
//此处的highlightBlock()方法用于动态渲染，从服务器端获取动态数据的页面渲染，测试时最好使用动态数据，不然会出现路由刷新/跳转后，高亮效果消失的情况
Vue.directive('highlight',function (el) {
  let blocks = el.querySelectorAll('pre code');
  blocks.forEach((block)=>{
    VueHighlightJS.highlightBlock(block)
  })
});

import ElementUI from 'element-ui'; //引入ElementUI插件
import 'element-ui/lib/theme-chalk/index.css'; //引入ElementUI的CSS
import Axios from 'axios'
import store from './store'

import locale from 'element-ui/lib/locale/lang/en'
Vue.use(ElementUI, { locale })

Vue.use(Vuetify, { theme: config.theme})

Vue.use(MyComponent)

//cron
import VueCron from 'vue-cron'
Vue.use(VueCron);

//vue-clipboard2
import VueClipboard from 'vue-clipboard2'
VueClipboard.config.autoSetContainer = true // add this line
Vue.use(VueClipboard)

Vue.prototype.$qs = qs;

Vue.config.productionTip = false;

Axios.defaults.headers.common['Authentication'] = store.state.token;
Axios.defaults.headers.common['RefreshToken'] = store.state.refresh_token;

const global_refresh_flag = {
  state: 0,
  url: ''
}; //全局token刷新回调标志

// 添加请求拦截器
Axios.interceptors.request.use(config => {
// 在发送请求之前做些什么
//判断是否存在token，如果存在将每个页面header都添加token
  if(store.state.token !== 'undefined' && store.state.token != null && store.state.token !== ''){
    config.headers.common['Authentication']=store.state.token;
    config.headers.common['RefreshToken'] = store.state.refresh_token;
  }else{
    router.push("/login")
  }

  return config;
}, error => {
// 对请求错误做些什么
  return Promise.reject(error);
});

  //接收来自服务端的accesstoken
  var webSocket;
  if(typeof(WebSocket) == "undefined") {
    console.log("您的浏览器不支持WebSocket");
  }
  webSocket = new WebSocket("ws://127.0.0.1:9001/tokenWebSocket");
  //获取来自服务端的消息
  webSocket.onmessage = function (resp) {
    console.log("来自tokenWebsocketServer的消息：" + JSON.stringify(resp.data));
    let str = resp.data;
    if(str === undefined){
      return;
    }
    if((typeof str) === 'string' && str.indexOf('连接成功') === -1){
      store.commit('set_token', resp.data);
      console.log('token刷新完毕！');
    }
  };
  webSocket.onclose = function (e) {
    console.log('tokenWebsocket 断开: ' + e.code + ' ' + e.reason + ' ' + e.wasClean);
    ElementUI.Message({
      message: '连接已断开！',
      type: 'error'
    })
  };

// http response 拦截器
Axios.interceptors.response.use(
  response => {
    console.log("拦截成功响应 -> " + JSON.stringify(response));
    if(response.data === ''){
      return ;
    }
    if(JSON.stringify(response.config.url).search('login') === -1 && JSON.stringify(response.config.url).search('logout') === -1){
      if(store.state.token !== response.config.headers.Authentication){
        Axios({
          method: response.config.method,
          url: response.config.url,
          data: response.config.data,
          headers: {
            "Accept": "application/json, text/plain, */*",
            "Authentication": store.state.token,
            "RefreshToken": store.state.refresh_token,
            "Content-Type": "application/json;charset=utf-8"
          },
        });
      }
    }

    //403无权访问处理
    if(response.errCode === 403 || response.data.errCode === 403){
      ElementUI.Message({
        message: '043：No auth to access [' + response.config.url + ']',
        type: 'error'
      })
    }

    //530 已登出处理
    if(response.errCode === 530 || response.data.errCode === 530){
      store.commit('del_token');
      store.commit('del_refresh_token');
      router.push('/login');
    }
    //532 refreshToken失效处理
    if(response.errCode === 532 || response.data.errCode === 532){
      store.commit('del_token');
      store.commit('del_refresh_token');
      router.push('/login');
    }
    return response;
  },
  error => {
    console.log("拦截错误响应 -> " + JSON.stringify(error.response));
    if (error.response) {
      switch (error.response.status) {
        case 401:
          store.commit('del_token');
          store.commit('del_refresh_token');
          router.replace({
            path: '/login',
            query: {redirect: router.currentRoute.fullPath}//登录成功后跳入浏览的当前页面
          });
      }
    }
    return Promise.reject(error.response.data)
  }
);

import Apis from './lib/api'
// import 'reset.css/reset.css'
import 'bpmn-js/dist/assets/diagram-js.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css'
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css'
import './components/bpmn/assets/css/vue-bmpn.css'
import 'element-ui/lib/theme-chalk/index.css'

// import './assets/css/element-ui.css'
// import './assets/css/iconfont.css'
Vue.prototype.Apis = Apis;

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store: store,
  components: { App },
  template: '<App/>'
})
